import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'
import {myAjax, ROOTURL} from './../publicAPI/publicAPI'

class BarberM extends Component {

	constructor (props, context) {
	    super(props, context);
	    console.log("初始化");
	    this.state = {
	    	page: 1,
	    	delete: false,
	    	deleteId: -1,
	    	barberData:[]
	    }; // 初始化状态

      this.start = 0; //从第几条获取理发师信息
			this.limit = 10;
			this.requestAll = false; //判断是否请求所有理发师数据

			this.getServants();
	}

	componentWillMount() {
		console.log("将安装")
	}

	componentDidMount() {
	    console.log("安装成功");

	}

	getServants() {
			let URL = ROOTURL +'servant/profile/search.api';
			fetch(URL, {
					method : 'POST',
					mode: 'cors',
					body: JSON.stringify({
							where: {
									dd: [
											["eq", false]
									],
									stActivate: [
											['eq', true]
									]
							},
						  "order": [["id", "asc"]],
              "start": this.start,
							"limit": this.limit
					})
			}).then(res=>{
					if(res.ok){
							res.json().then(data=>{
								// console.log('----------');
									console.log(data.length);
									// console.log('----------');
									var data2 = [];
									for(var k=0; k<data.length; k++){
										if(!(data[k].dd)){
											data2.push(data[k]);
										}
									}
									if(data2.length < this.limit) {
							    		this.requestAll = true
						    	} else {
											this.requestAll = false
									}
									this.setState({
										 barberData:data2
									})
							})
					}
			})
	}

	handleClick() {

		fetch('https://api.github.com/users/js', {
		    method: 'GET',
		    headers: {
		      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
		    },
			 // body: 'login=KingJch'
			})
			.then(response => console.log(response))
			.then(function (data) {
			    console.log('Request succeeded with JSON response', data);
			})
			.catch(function (error) {
			    console.log('Request failed', error);
			});

		this.setState({page: this.state.page+1 })
	}

	handleDelete(id) {
		this.setState({
			delete: !this.state.delete,
			deleteId: id
		})
	}

	deleteBarber(){
			var _this = this;
			var param = {
				// id:this.state.deleteId
			}
	       var URL1 = ROOTURL + 'barber/profile/instance.api?id=' + this.state.deleteId;
	       // alert(this.state.deleteId);
	       fetch(URL1,{
	           method: 'DELETE',
	           headers: {
                	"Content-type": "application/json; charset=UTF-8"
             	},
	           body: param
	       }).then(function (res) {
	           if (res.ok){
	               console.log('delete success');
	               var barber = _this.state.barberData;
	               barber.map(function (result,index) {
	                   if(result.id == _this.state.deleteId){
	                       barber.splice(index,1);
	                       _this.setState({
	                           barberData: barber
	                       })
	                   }
	               })

	           }else{
	               console.log(res)
	           }
	       });
	       this.setState({
	           delete: !this.state.delete
	       });
	}

	tHead() {
		var data = [
			{name: "id"},
			{name: "姓名"},
			{name: "userid"},
			{name: "手机号"},
			{name: "所属门店"},
			{name: "操作"}
		];
		const _headArr = [];
		const _width = {
			"0" : "14.6%",
			"1" : "14.8%",
			"2" : "16.3%",
			"3" : "14.9%",
			"4" : "19.7%",
			"5" : "19.7%"
		};
		//_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
		_headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
		return _headArr;
	}

	tBody() {
				return this.state.barberData.map(item => <tr key={item.id}>
					<td>{item.id}</td>
					<td>{item.meta.name}</td>
					<td>{item.userid}</td>
					<td>{item.meta.phone}</td>
					<td>{item.meta.shop}</td>
					<td>
						<span><NavLink  to={`/BarberM/AddBarber/${item.id}`} className="rbtn green">查看</NavLink></span>
						<span style={{marginLeft: "15px"}}><NavLink  to={`/OrderM/${item.name}`} className="rbtn green">查看订单</NavLink></span>
						<span style={{marginLeft: "15px"}}><a  className="rbtn red" onClick={() => this.handleDelete(item.id)}>删除</a></span>
					</td>
				</tr>)
	}

	//翻页按钮
	handlePageClick(e) {//1为下一页，2为上一页
			const _buttonValue = e.target.value

			if(_buttonValue == 1) {
				this.start = this.start + this.limit

			} else {
				this.start = this.start - this.limit
			}
			this.getServants();
	}

    render() {console.log("理发师管理" + "渲染" + this.state.page)




	    return (
	    	<div className="right-wapper ">
				<div className="rt-wrap">
					<h2 className="catagory" onClick={() => this.handleClick()}>
						<span className="cata-title">理发师管理</span>
						<button className="next" value="1" style={{display: this.requestAll ? "none" : "block"}} onClick={(e) => this.handlePageClick(e)}></button>
						<button className="prev" value="2" style={{display: this.start ? "block" : "none"}} onClick={(e) => this.handlePageClick(e)}></button>
						<Link to={`/BarberM/AddBarber`}>
							<button className="add-btn" />
						</Link>
					</h2>

					<Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()} />
				</div>
				{ this.state.delete ?
					<div id={style.msgDialog}>
						<div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
							<div className={style['msgDialog_button']}>
								<button id={style['msgDialog_yes']} onClick={this.deleteBarber.bind(this)}>确定</button>
								<button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
							</div>
						</div>
					</div> : null}
	    	</div>
	    )
	  }
}

 export default BarberM
